import axios from 'axios'
import { Message, Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { baseURL } from './baseURL'
import { baseURL1 } from './baseURL'

function queryParse(query) {
  const res = []
  for (const k in query) {
    res.push(`${encodeURIComponent(k)}=${encodeURIComponent(query[k])}`)
  }
  return res.join('&')
}

// 定义请求基地址变量，测试服，旧版
// const baseURL = 'http://192.168.121.67:8110'
// const baseURL1 = 'http://192.168.121.67:8110'
// 华海联能后台
// const baseURL = 'https://www.golwayhhln.top/hhlnMes'
// 赫能士后台
// const baseURL = 'https://www.golwayhhln.top/hnsMes'

const service = axios.create({
  baseURL,
  timeout: 250 * 1000
})

// export const json2fd = json => {
//   const fd = new FormData()
//   for (let k in json) {
//     fd.append(k, json[k])
//   }
//   return fd
// }

// 请求拦截器（在请求之前进行一些配置）
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    if (config.params && config.params.isSpray || config.data && config.data.isSpray) {
      config.baseURL = baseURL1
      if (config.params) { delete config.params.isSpray }
      if (config.data) { delete config.data.isSpray }
    }
    // 优先判断：如果请求已手动指定 Content-Type，则优先尊重调用者
    const contentType = config.headers['Content-Type'] || config.headers['content-type'];
    if (contentType) {
      if (contentType.includes('application/json') && typeof config.data !== 'string') {
        config.data = JSON.stringify(config.data);
      } else if (contentType.includes('application/x-www-form-urlencoded')) {
        config.data = queryParse(config.data);
      }
      // 若是 multipart/form-data 等其他格式，这里也可继续扩展处理
      return config;
    }
    if (config.url == '/back/user-knowledge-record/upd' || config.url == '/system/role/dataScope' || config.url == '/system/role/changeStatus' || config.url == '/system/role' || config.url == '/system/dict/data' || config.url == '/system/dict/type' || config.url == '/system/dept' || config.url == '/back/processJobClass/saveProcessJobClassCodeEms' || config.url == '/device/NumericalControl/word02' || config.url == '/back/processJobClass/addTechnologyNoProcess' || config.url == '/back/money-config/verifyEquation' || config.url == '/ems-facility-maintenance/word03' || config.url == '/ems-facility-verif-test/upd' || config.url == '/device/word04' || config.url == '/device/word04_download' || config.url == '/device/word05_download' || config.url == '/device/word05' || config.url == '/back/user-knowledge-record/saveList' || config.url == '/back/user-knowledge-record/updList' || config.url == '/customer-inspection-form/add' || config.url == '/back/user-knowledge-post/getById' || config.url == '/back/user-knowledge-post-critical-process/save' || config.url == '/back/user-knowledge-record/userKnowledgeRecordState') {
      config.headers['Content-Type'] = 'application/json'
      config.data = JSON.stringify(config.data)
    } else {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
      config.data = queryParse(config.data)
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// 响应了拦截器
service.interceptors.response.use(
  response => {
    console.log('%c [ response ]-77', 'font-size:13px; background:pink; color:#bf2c9f;', response)
    // 下载文件流类型处理（Blob 或 ArrayBuffer）
    const contentType = response.headers['content-type']
    const isBlob = contentType && (contentType.includes('application/octet-stream') || contentType.includes('application/pdf') || contentType.includes('application/vnd'))

    if (isBlob) {
      // 直接返回整个 response.data，用于前端直接下载
      return response.data
    }

    const res = response.data
    if (res.code === 1 || res.code === 79) {
      return res
    } else if (res.code === 403 || res.code === 2) {
      Notification({
        title: '警告',
        message: '您的登录凭证已过期，请重新登录,2秒后自动退出系统',
        type: 'warning'
      })
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    } else if (res.code === 3) {
      Notification({
        title: '警告',
        message: '用户未登录',
        type: 'warning'
      })
    } else if (res.code === 21) {
      Notification({
        title: '警告',
        message: '您的权限不足',
        type: 'warning'
      })
    } else {
      Message({
        message: res.msg || '系统异常',
        type: 'error',
        duration: 5 * 1000
      })
      return res
      // return Promise.reject(res) // 若你希望失败后终止流程，可取消注释
    }
  },
  error => {
    Message({
      message: error.message || '请求失败',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 将我们的axios实例暴露出去
export default service
